package ai.iyoga.dao;

import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;

import ai.iyoga.been.Member;
import ai.iyoga.util.TransactionManager;

public class MemberDao {

	public void addMembre(Member mem) {
		try {
			String sql = "INSERT INTO member (NAME, ADDR, CAREER) VALUE(?, ?, ?)";
			
			QueryRunner runner = new QueryRunner(TransactionManager.getSource());
			runner.update(sql, mem.getName(), mem.getAddr(), mem.getCareer());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public Member findMemberByName(String name){
		try {
			String sql = "SELECT * FROM member WHERE NAME=?";
			
			QueryRunner runner = new QueryRunner(TransactionManager.getSource());
			Map<String, Object> queryRes = runner.query(sql, new MapHandler(), name);
			
			if(queryRes == null || queryRes.size() == 0){
				return null;
			}
			
			Member mem = new Member();
			mem.setMemNo((Integer)queryRes.get("MEM_NO"));
			mem.setName((String)queryRes.get("NAME"));
			mem.setCareer((String) queryRes.get("CAREER"));
			mem.setAddr((String) queryRes.get("ADDR"));
			
			return mem;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public Member findMemberByNo(int memNo){
		try {
			String sql = "SELECT * FROM member WHERE MEM_NO=?";
			
			QueryRunner runner = new QueryRunner(TransactionManager.getSource());
			Map<String, Object> queryRes = runner.query(sql, new MapHandler(), memNo);
			
			if(queryRes == null || queryRes.size() == 0){
				return null;
			}
			
			Member mem = new Member();
			mem.setMemNo((Integer)queryRes.get("MEM_NO"));
			mem.setName((String)queryRes.get("NAME"));
			mem.setCareer((String) queryRes.get("CAREER"));
			mem.setAddr((String) queryRes.get("ADDR"));
			
			return mem;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

}
